package middleware

import (
	"cr.org/constant"
	"cr.org/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
)

func JWTAuth(subject string) gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get(constant.Token)
		if token == "" {
			c.Error(&gin.Error{Err: errors.New(constant.ErrorMap[constant.ErrorUnauthorized]), Type: constant.ErrorUnauthorized}) // nolint
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		token = token[len(constant.TokenPre):]
		j := utils.NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == utils.TokenExpiredAt { // nolint
				c.Error(&gin.Error{Err: errors.New(constant.ErrorMap[constant.ErrorUnauthorized]), Type: constant.ErrorUnauthorized}) // nolint
				c.AbortWithStatus(http.StatusUnauthorized)
				return
			}
			c.Error(&gin.Error{Err: errors.New(constant.ErrorMap[constant.ErrorUnauthorized]), Type: constant.ErrorUnauthorized}) // nolint
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		c.Set("claims", claims)
		c.Next()
	}
}
